<template>
  <Row :gutter="10">
    <template v-for="(item, index) in sourceList" :key="index">
      <Col span="6">
        <Card shadow>
          <template #title>{{ item.title }}</template>
          <template #extra>
            <Link @click="onInstall(item)">安装</Link>
          </template>
          <p v-if="item.version">版本：{{ item.version }}</p>
          <div style="display: flex">
            <div>地址：</div>
            <div class="over-ellipsis link-style" :title="item.url" style="flex: 1" @click="openBrowser(item.url)">
              {{ item.url }}
            </div>
          </div>
          <p>描述：{{ item.desc }}</p>
        </Card>
      </Col>
    </template>
  </Row>
  <Modal
    :width="700"
    v-model="installOpen"
    :title="`安装${currentItem?.title || ''}`"
    @on-ok="onInstallSubmit">
    <Form :label-width="90">
      <FormItem label="发行地址：">
        <div v-if="currentItem" class="link-style" :title="currentItem?.release || ''" style="flex: 1"
             @click="openBrowser(currentItem?.release || '')">{{ currentItem?.release || '' }}
        </div>
      </FormItem>
      <FormItem label="版本：">
        {{ currentReleases?.name || '--' }}
      </FormItem>
      <FormItem label="安装位置：">
        <Input v-model="installPath" search enter-button="选择..." placeholder="应用安装位置" @on-search="onChoosePath"/>
      </FormItem>
    </Form>
  </Modal>
  <Modal
    :width="700"
    v-model="installScheduleOpen"
    @on-cancel="onInstallClose"
    :mask-closable="false"
    :title="`安装进度`"
    footer-hide>
    <Steps :current="currentInstallStep" :status="currentInstallStatus" direction="vertical">
      <Step title="准备" content="用户选择安装位置等信息"></Step>
      <Step title="下载文件" content="下载对应的安装文件"></Step>
      <Step title="解压" content="解压安装文件"></Step>
      <Step title="配置" content="配置环境"></Step>
      <Step title="完成" content="完成"></Step>
    </Steps>
  </Modal>
  <Modal
    :width="500"
    v-model="installProgressOpen"
    @on-cancel="onInstallProgressClose"
    :mask-closable="false"
    :title="`下载进度`"
    footer-hide>
    <Progress :percent="Number((installProgress / installProgressTotal * 100).toFixed(2))" status="active"/>
  </Modal>
</template>

<script lang="ts" setup>
import sourceList, {SourceType} from "../data/source";
import {getReleases} from "@/api/common";
import {GithubAsset, GithubReleasesType} from "@/types/GithubReleasesType";
import {Message} from "view-ui-plus";
import {Ref, ref} from "vue";
import Downloader from "@/utils/Downloader";

defineOptions({name: 'EnvironmentContent'})

let currentItem: Ref<SourceType | null> = ref(null);

let installOpen = ref(false);

let installScheduleOpen = ref(false);

let installPath = ref('');

let currentReleases: Ref<GithubReleasesType | null> = ref(null);

let currentInstallStep: Ref<number> = ref(0);
let currentInstallStatus: Ref<'wait' | 'process' | 'finish' | 'error'> = ref('wait');

let installProgressOpen: Ref = ref(false);
let installProgress: Ref<number> = ref(0);
let installProgressTotal: Ref<number> = ref(100);

const openBrowser = (url: string) => {
  // @ts-ignore
  window.electronAPI.windowToControlWarn(url);
}

const onInstall = (item: SourceType) => {
  currentItem.value = item;
  installOpen.value = true;
  getReleases(currentItem.value.username, currentItem.value.repository).then(res => {
    currentReleases.value = res;
  })
}

const onInstallSubmit = () => {
  if (!currentItem.value) return;
  if (!currentReleases.value) {
    Message.warning('未获取到资源')
    return;
  }
  if (!installPath.value) {
    Message.warning('请选择安装位置')
    return;
  }
  const assets: GithubAsset[] = currentReleases.value.assets;
  if (assets && assets.length <= 0) {
    Message.warning('未获取到资源')
    return;
  }
  const asset = assets.find(item => item.content_type === 'application/x-zip-compressed');
  if (!asset) {
    Message.warning('未获取到资源')
    return;
  }
  installScheduleOpen.value = true;
  currentInstallStep.value = 1;
  // @ts-ignore 下载
  window.electronAPI.download(assets[0].browser_download_url, installPath.value);
  return;
  installProgressOpen.value = true
  // @ts-ignore 下载错误
  window.electronAPI.onReleaseDownloadError(() => {
    installProgressOpen.value = false;
    onInstallProgressClose();
    currentInstallStatus.value = 'error';
  });
  // @ts-ignore 下载成功
  window.electronAPI.onReleaseDownloadSuccess(() => {
    installProgressOpen.value = false;
    unzip(asset);
  });
  // @ts-ignore 下载监听
  window.electronAPI.onReleaseDownload(progress => {
    console.log('监听下载')
    installProgressTotal.value = progress.total;
    installProgress.value = installProgress.value + progress.current;
  });
}

const unzip = (asset: GithubAsset) => {
  currentInstallStep.value = 2;
  // @ts-ignore 解压
  window.electronAPI.unzip(installPath.value + "\\" + asset.name, installPath.value).then(zipRes => {
    console.log("解压结果", zipRes)
    if (zipRes) {
      currentInstallStep.value = 3;
    } else {
      currentInstallStatus.value = 'error';
    }
  })
}

const onChoosePath = () => {
  // @ts-ignore
  window.electronAPI.chooseFolder().then(res => {
    if (res) {
      installPath.value = res[0];
    }
  })
}

const resetProgress = () => {
  installProgressTotal.value = 100;
  installProgress.value = 0;
}

const onInstallProgressClose = () => {
  resetProgress();
  installProgressOpen.value = false;
  // @ts-ignore
  window.electronAPI.closeReleaseDownload();
}

const onInstallClose = () => {
  resetProgress();
  currentInstallStatus.value = 'wait';
  currentInstallStep.value = 0;
  installScheduleOpen.value = false;
  // @ts-ignore
  // window.electronAPI.closeReleaseDownload();
}
</script>

<style scoped>

</style>
